import os
import json  # 新增：用于解析JSON映射文件

def load_local_knowledge():
    """读取本地知识库文档（保持不变）"""
    knowledge_path = "/usr/local/knowledge_base/knowledge.md"
    if not os.path.exists(knowledge_path):
        print(f"警告：未找到知识库文件 {knowledge_path}")
        return ""
    try:
        with open(knowledge_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception as e:
        print(f"读取知识库失败：{e}")
        return ""

def load_script_by_code_id(code_id):
    """根据code_id从新知识库结构加载Shell脚本"""
    # 1. 定义JSON映射文件和脚本文件夹路径
    mapping_file = "/usr/local/knowledge_base/fault_script_mapping.json"
    scripts_dir = "/usr/local/knowledge_base/scripts"
    
    # 2. 检查映射文件是否存在
    if not os.path.exists(mapping_file):
        print(f"映射文件不存在：{mapping_file}")
        return None
    
    # 3. 读取并解析JSON映射
    try:
        with open(mapping_file, "r", encoding="utf-8") as f:
            script_mapping = json.load(f)
    except json.JSONDecodeError:
        print(f"JSON解析失败：{mapping_file} 格式错误")
        return None
    except Exception as e:
        print(f"读取映射文件失败：{e}")
        return None
    
    # 4. 获取脚本相对路径
    script_rel_path = script_mapping.get(code_id)
    if not script_rel_path:
        print(f"未在映射文件中找到 code_id：{code_id}")
        return None
    
    # 5. 拼接完整脚本路径（处理相对路径可能的层级问题）
    script_path = os.path.abspath(os.path.join(scripts_dir, script_rel_path))  # 使用abspath确保绝对路径
    if not os.path.exists(script_path):
        print(f"脚本文件不存在：{script_path}（绝对路径）")
        return None
    
    # 6. 读取脚本内容
    try:
        with open(script_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception as e:
        print(f"读取脚本 {script_path} 失败：{e}")
        return None

def execute_script(script_content):
    """执行修复脚本内容（保持不变）"""
    if not script_content:
        print("没有可执行的脚本内容")
        return False
        
    try:
        import subprocess
        result = subprocess.run(
            script_content, 
            shell=True, 
            check=True, 
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE,
            text=True
        )
        print(f"脚本执行成功：{result.stdout}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"脚本执行失败：{e.stderr}")
        return False